package com.my.lock.v1;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

/**
 * Created by ZhongGang
 * at 2018/7/27 10:27
 */
public class NonReentrantLock {
    private AtomicBoolean locked = new AtomicBoolean(false);//标识是否已有线程持有锁
    private Queue<Thread> waiters = new ConcurrentLinkedQueue<>();//等待获取锁的线程

    public void lock() {
        if (!this.locked.compareAndSet(false, true)) {
            Thread thread = Thread.currentThread();
            this.waiters.add(thread);
            LockSupport.park(this);
        }
    }

    public void unlock() {
        this.locked.set(false);
        Thread nextThread = this.waiters.poll();
        LockSupport.unpark(nextThread);
    }
}
